package com.example.model_user.login

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.launcher.ARouter
import com.chendechao.lib_base.BaseActivity
import com.chendechao.lib_common.ARouterCdd
import com.example.model_user.R
import com.example.model_user.databinding.ActivityLoginBinding
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>(ActivityLoginBinding::inflate) {
    override val viewModel: LoginViewModel by viewModels()
    val mmkv = MMKV.defaultMMKV()
    override fun initView() {
        binding.apply {
            etUsername.addTextChangedListener { username ->
                viewModel.sendEvent(LoginIntent.UsernameChanged(username.toString()))
            }
            etPassword.addTextChangedListener { password ->
                viewModel.sendEvent(LoginIntent.PasswordChanged(password.toString()))
            }
//            // 从 MMKV 获取保存的用户名和密码
//            val savedUsername = mmkv.decodeString("username", "")
//            val savedPassword = mmkv.decodeString("password", "")
//
//            // 将保存的用户名和密码设置到输入框中
//            etUsername.setText(savedUsername)
//            etPassword.setText(savedPassword)
            //1.登录按钮点击事件
            btnLogin.setOnClickListener {
                //2.发送登录
                viewModel.sendEvent(LoginIntent.LoginClicked)

            }
            loginRegister.setOnClickListener {
                ARouter.getInstance().build(ARouterCdd.REGISTER).navigation()
            }
        }

    }

    override fun initData() {
        //22,收集具体处理方式
        collectState(viewModel.state){ state ->
            updateUI(state)
        }

    }
    // 23,更新UI
    private fun updateUI(state: LoginUiState){
        binding.apply {
            if(state.isLoading){

            }
            if(state.isSucess){

                ARouter.getInstance().build(ARouterCdd.HOME_ACTIVITY).navigation()
                Log.i("TAG", "updateUI: ${state.userInfo}")

            }
        }
    }

}